package com.voice.call.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.voice.call.common.Const;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.CallLog;
import com.voice.call.mapper.CallLogMapper;
import com.voice.call.service.VosCallBackService;
import com.voice.call.utils.HttpTransport;
import com.voice.call.utils.JSONUtil;
import com.voice.call.utils.MD5Util;
import com.voice.call.utils.StringUtil;

@Service
public class VosCallBackServiceImpl implements VosCallBackService{
	
	private static final Logger log = LoggerFactory.getLogger(VosCallBackServiceImpl.class);
	private static final String app_key = "6RT&pE%g6f";
	private static final String app_secret = "ZTDm8iV#M$nQ%iSh";
	
	
	@Resource
	private CallLogMapper  callLogMapper;
	
	/**
	 * 获取可拨打多少秒
	 * @param uid
	 * @param caller
	 * @param called
	 * @return
	 */
	@Override
	public String getLeftTime(String urlStr,String uid,String caller,String called) {
		
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		bodyMap.put("uid", uid);
		bodyMap.put("caller", caller);
		bodyMap.put("called", called);
		Result rs = post(urlStr, bodyMap);
		log.info("sgcall call left time:{}",JSONUtil.objectToJson(rs));
		if (rs.getCode() == ResultEnum.SUCCESS.getCode()) {
			
			Map<String, Object> rsMap = (Map<String, Object>)rs.getData();
			if (rsMap!=null && rsMap.get("leftTime")!=null) {
				return rsMap.get("leftTime").toString().trim();
			}
			
		}
		return "0";
	}
	
	//话单回调
	@Override
	public	void visionCallBill(String urlStr,CallLog callLog) {
		new Thread(new ThirdCallLogThread(urlStr,callLog,this)).start();
	}
	@Override
	public	void visionCallLogCallBack(int times,String urlStr,CallLog callLog) {
		Map<String,Object> bodyMap = new HashMap<String,Object>();
		bodyMap.put("callLog", JSONUtil.objectToJson(callLog));
		Result rs = post(urlStr, bodyMap);
		if (rs.getCode() == ResultEnum.SUCCESS.getCode()) { //成功
			log.info("vision话单回调成功");
			CallLog updateLog = new CallLog();
			updateLog.setId(callLog.getId());
			updateLog.setStatus(Const.Y);
			if (callLogMapper.update(updateLog)>0) {
				log.info("vision话单同步成功");
			}else {
				log.error("vision话单同步失败");
			}
		}else {//失败
			if (times>0) {
				times--;
				visionCallLogCallBack(times,urlStr,callLog);
			}
			log.error("vision话单回调失败");
		}
	}
	
    private Result post(String urlStr,Map<String, Object> params) {
		
		try {
			
			
			log.info("sgcall request url:{}",urlStr);
			long t1=System.currentTimeMillis()/1000;
			String timestamp = String.valueOf(t1);
			String noncestr = StringUtil.buildRandomCode(10);
			
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			bodyMap.put("agentCode", "zxst");
			bodyMap.put("pv", "third");
			bodyMap.put("v", "1.0.0");
			bodyMap.put("lang", "en");
			bodyMap.put("timestamp", timestamp);
			bodyMap.put("noncestr", noncestr);
			
			if (params!=null && !params.isEmpty()) {
				bodyMap.putAll(params);
			}
			
			String sign = MD5Util.md5Hex(app_key+noncestr+timestamp+app_secret);
			bodyMap.put("sign", sign);
			String requestBody = JSONUtil.mapToJson(bodyMap);
			log.info("sgcall request params:{}",requestBody);
			
			HttpTransport httpRequest = HttpTransport.getInstance();
			String jsonStr = httpRequest.doJSONPost(urlStr, requestBody);
			log.info("sgcall request result:{}",jsonStr);
			if (!StringUtil.isEmpty(jsonStr)) {
				return JSONUtil.jsonToObject(jsonStr, Result.class);
			}
			log.error("sgcall request failed");
			return new Result(ResultEnum.FAILED);
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("sgcall request exception");
			return new Result(ResultEnum.FAILED);
		}
		
	}

}

class ThirdCallLogThread implements Runnable {
	CallLog callLog;
	VosCallBackService deliverService;
	String callbackUrl;

	ThirdCallLogThread() {
	}

	ThirdCallLogThread(String urlStr,CallLog callLog, VosCallBackService deliverService) {
		this.callbackUrl = urlStr;
		this.callLog = callLog;
		this.deliverService = deliverService;
	}

	@Override
	public void run() {
		//失败会重试二次
		deliverService.visionCallLogCallBack(2,callbackUrl,callLog);
	}
}